// Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using System.Data.SqlClient;

namespace PfRep.Library
{
    public static class Management
    {
        /// <summary>
        /// Creates the PfRep database
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="databaseName"></param>
        /// <param name="databaseScript"></param>
        public static void CreatePfRepDatabase(
            string connectionString,
            string databaseName)
        {
            // Calcualte the SQL script's path
            //string executionPath = Assembly.GetExecutingAssembly().Location;
            //executionPath = executionPath.EndsWith(@"\") ? executionPath : executionPath + @"\";
            string executionPath = "Database.sql";

            // Open the SQL script
            Common.Diagnostics.Trace("PfRepLib.CreatePfRepDatabase",
                "Going to read database file " + executionPath + " from the execution folder");
            StreamReader sqlScriptStreamReader = new StreamReader(executionPath);
            Common.Diagnostics.Trace("PfRepLib.CreatePfRepDatabase",
                "Database file red succesfully");

            // Call to DA layer
            DataAccess.SQL.CreatePfRepDatabase(connectionString, databaseName, 
                sqlScriptStreamReader.ReadToEnd());
        }

        /// <summary>
        /// Checks whether the specified connection string works
        /// </summary>
        /// <param name="connectionString">Connection string to check</param>
        /// <returns>true if the connection can be opened, otherwise false.</returns>
        public static bool IsDatabaseExists(string connectionString)
        {
            try
            {
                using (SqlConnection connection = 
                    DataAccess.SQL.CreateConnection(connectionString))
                {
                    return true;
                }
            }
            catch (SqlException)
            {
                return false;
            }
        }
    }
}
